<?php

App::uses('AppModel', 'Model');

/**
 * Subscription Model
 *
 * @property User $User
 * @property SubscriptionTerm $SubscriptionTerm
 * @property Payment $Payment
 */
class Subscription extends AppModel {

    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'id';
    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array();
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'SubscriptionTerm' => array(
            'className' => 'SubscriptionTerm',
            'foreignKey' => 'subscription_term_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Payment' => array(
            'className' => 'Payment',
            'foreignKey' => 'payment_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    /**
     *
     * @var type 
     */
    public $paypal = null;

    /**
     *
     * @param type $userId
     * @param type $plan
     * @param type $data
     * @param type $paymentMethod
     * @return type 
     */
    public function newSubscride($userId, $plan, $data = array(), $paymentMethod = PICKUP_METHOD) {

        if ($plan == 0 && !empty($data)) {
            $plan = $this->SubscriptionTerm->getPlan($data['Subscription']['subscription_term_id']);
        }

        $expire_date = mktime(date('s'), date('i'), date('h'), date('m') + $plan, date('d'), date('Y'));
        $alert_expire = mktime(date('s'), date('i'), date('h'), date('m') + $plan, date('d') - DATE_ALERT_BEFORE_EX, date('Y'));


        if (!empty($data)) {
            $data['Subscription']['expire_alert'] = date('Y-m-d h:i:s', $alert_expire);
            $data['Subscription']['expire_date'] = date('Y-m-d h:i:s', $expire_date);
            $data['Subscription']['payment_method'] = $paymentMethod;
        } else {
            $data['Subscription'] = array(
                'expire_alert' => date('Y-m-d h:i:s', $alert_expire),
                'expire_date' => date('Y-m-d h:i:s', $expire_date),
                'subscription_term_id' => $this->SubscriptionTerm->getTermId($plan),
                'user_id' => $userId,
                'active' => SUBSCRIPTION_STATUS_WAITING_CONFIRM_EMAIL,
                'payment_method' => $paymentMethod
            );
        }

        $this->create();
        $this->data = $this->save($data, false);
        $this->data[$this->alias]['id'] = $this->id;
        
        if (!empty($this->data)) {
            $data = $this->data;
            if ($paymentMethod == PICKUP_METHOD) {
                $payment['Payment'] = array(
                    'payment_gross' => $this->SubscriptionTerm->getPrice($this->data[$this->alias]['subscription_term_id']),
                    'payment_status' => PAYMENT_STATUS_PENDING,
                    'payment_date' => date('Y-m-d h:i:s'),
                    
                );
                $paymentId = $this->Payment->savePayment($payment);
                $this->saveField('payment_id', $paymentId);
            }
            return $data;
        }

        return false;
    }

    public function getTerm($id, $all = false) {
        $subs = $this->find('first', array(
                    'conditions' => array('Subscription.id' => $id),
                    'contain' => 'SubscriptionTerm'
                ));
        if ($all) {
            return $subs;
        } 
        return $subs['SubscriptionTerm']['term'];
    }
    
    public function updatePlan($id, $plan) {

        $this->id = $id;
        $this->saveField('subscription_term_id', $this->SubscriptionTerm->getTermId($plan));
    }

    public function existSubscribe($userId) {
        $count = $this->find('count', array('conditions' => array('Subscription.user_id' => $userId, 'Subscription.active' => 1)));
        if ($count) {
            return true;
        }
        return false;
    }

    public function changeStatus($userId) {
        $this->updateAll(array('Subscription.active' => SUBSCRIPTION_STATUS_PADDING), array('Subscription.user_id' => $userId, 'Subscription.active' => -2));
    }

    public function cleanExpired() {
        $this->updateAll(array('Subscription.active' => SUBSCRIPTION_STATUS_EXPIRED), array('Subscription.active >= ' => 0, 'Subscription.expire_date < ' => date('Y-m-d H:i:s')));
    }

    public function is_valid($data) {
        if (!empty($data)) {
            App::uses('PaypalIpnSource', 'Model/Datasource');
            $this->paypal = new PaypalIpnSource();
            return $this->paypal->isValid($data);
        }
        return false;
    }

    /**
     * builds the associative array for paypalitems only if it was a cart upload
     *
     * @param raw post data sent back from paypal
     * @return array of cakePHP friendly association array.
     */
    public function buildAssociationsFromIPN($post) {
        $retval = array();
        $retval['Payment'] = $post;

        $number = explode('-', $post ['item_number']);
        $id = end($number);
        $this->id = $id;
        if ($this->exists()) {
            $payment= $this->Payment->checkIPNID($post['txn_id']);
            $isExist = false;
            if (!empty($payment) && isset($payment['Payment']['id'])) {
                $this->Payment->id = $payment['Payment']['id'];
                $isExist = true;
            } else {
                $this->Payment->create();
            }
            if ($this->Payment->save($retval)) {
                $data = $this->Payment->read(null, $this->Payment->id);
                if ($data['Payment']['payment_status'] == 'Completed' && $data['Payment']['actived'] == 0) {
                    $this->Payment->saveField('actived', 1);
                    $this->log('Payment has been Completed.', 'paypal');
                    $this->saveField('active', SUBSCRIPTION_STATUS_ACTIVE);
                    $this->saveField('payment_id', $this->Payment->id);
                    
                    $this->User->activeUser($number[1]);
                    
                    return $data;
                }
                $this->log('Payment has been completed.', 'paypal');
                return true;
                
            } else {
                $this->log('Payment could not save.', 'paypal');
                return false;
            }
        } else {
            $this->log('Invalid Subscription', 'paypal');
        }

        return false;
    }

}
